package com.example.haxballandroid;

import java.util.ArrayList;
import java.util.Arrays;

import phone.beans.GameServerBean;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class JoinActivity extends Activity {

	private ListView serverList;
	private ArrayAdapter<String> listAdapter;
	private String[] servers;
	private boolean join = false;
	private Intent intent;
	private Bundle bundle;
	private GameServerBean[] beans;
	public final static String JOIN = "com.example.haxballandroid.MESSAGE";
	public final static String REFRESH = "com.example.haxballandroid.MESSAGE";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_join);
		intent = new Intent(this, ActionUpdate.class);
//		registerReceiver(broadcastReceiver, new IntentFilter(ActionUpdate.BROADCAST_ACTION));
		// Show the Up button in the action bar.
		
		//Update the UI with the list of servers
		init();
		
		
	}
		
	

	public BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){
		
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			
			updateUI();
		}

	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_join, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void sendRefresh(View view){
		intent = new Intent(this, ActionUpdate.class);
		intent.putExtra(REFRESH, "refresh");
		startService(intent);
	}
	
	//Updating the UI with new list of game servers and status of a join request sent to the lobby
	public void updateUI(){
		if(!join){
			//Adds the servers to the screen
			populateList();
		}
		else{
			//If it is a join succesful, takes you to game field or else displays error message
			if(ActionUpdate.joinStatus){
				joinSuccessful();
			}
			else{
				AlertDialog.Builder alert = new AlertDialog.Builder(this);

				alert.setTitle("Alert");
				alert.setMessage("The password you have entered is wrong");

				
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				  dialog.cancel();
				  }
				});
				alert.show();
			}
			//after attempt to join a server is over
			join = false;
		}
		
		
	}
	
	//Updates the list of game servers whenever refresh is hit
	public void populateList(){
		serverList = (ListView) findViewById(R.id.serverListView);
		serverList.setOnItemClickListener(new OnItemClickListener(){
			//When the user clicks on a server he wishes to join
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				authenticateServer(arg1, arg2);
			}
			
		});
		
		//Populate the list
		beans = ActionUpdate.gBeans;
		
		if(beans!=null && beans.length >0){
//			Log.d("Length", ""+beans.length);
			servers = new String[beans.length];
			for(int i =0; i<beans.length;i++){
				servers[i] = beans[i].getName();
//				Log.d("game", servers[i]);
			}
			ArrayList<String> server = new ArrayList<String>();
			server.addAll(Arrays.asList(servers));
			listAdapter = new ArrayAdapter<String>(this, R.layout.rowtextview, server);
			listAdapter.notifyDataSetChanged();
			serverList.setAdapter(listAdapter);
			serverList.setVisibility(View.GONE);
			serverList.setVisibility(View.VISIBLE);
			
		}		
		else{
			
			Log.d("Toast", "toast");
			serverList.setVisibility(View.GONE);
			
			Context context = getApplicationContext();
			CharSequence text = "No Game Servers Exist!";
			int duration = Toast.LENGTH_SHORT;

			Toast toast = Toast.makeText(context, text, duration);
			toast.show();
		}
	}
	
	//Checks if the server has password, if yes prompts the user for the password and sends it to the server
	protected void authenticateServer(View arg1, int arg2) {
		final int position = arg2;
		if(beans[arg2].isHasPassword()){
			//Displaying a dialog box to get password
			AlertDialog.Builder alert = new AlertDialog.Builder(this);

			alert.setTitle("Title");
			alert.setMessage("Please enter the password");

			// Set an EditText view to get user input 
			final EditText input = new EditText(this);
			alert.setView(input);

			alert.setPositiveButton("Join", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			  String value = input.getText().toString();
			  sendJoinMessage(position, value);
			  }
			});

			alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			  public void onClick(DialogInterface dialog, int whichButton) {
			    dialog.cancel();
			  }
			});

			alert.show();
		}
		else{
			sendJoinMessage(position, "");
		}
		
	}
	
	//Sending the join message to the server
	public void sendJoinMessage(int position, String password){
		join = true;
		Intent intentServ = new Intent(this, ActionUpdate.class);
		intentServ.putExtra(JOIN, "join");
		intentServ.putExtra("GameName", servers[position]);
		intentServ.putExtra("Password", password);
		startService(intentServ);
		
	}
	
	//starts the game field activity when the user successfully joined the game
	public void joinSuccessful(){
		Intent intentAct = new Intent(this, TeamActivity.class);
//		intent = new Intent(this, ActionUpdate.class);
		
		startService(intent);
		startActivity(intentAct);
	}
	
	public void init(){
		serverList = (ListView) findViewById(R.id.serverListView);
		serverList.setOnItemClickListener(new OnItemClickListener(){
			//When the user clicks on a server he wishes to join
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				authenticateServer(arg1, arg2);
			}
			
		});
		
		beans = ActionUpdate.gBeans;
		
		if(beans!=null && beans.length >0){
//			Log.d("Length", ""+beans.length);
			servers = new String[beans.length];
			for(int i =0; i<beans.length;i++){
				servers[i] = beans[i].getName();
//				Log.d("game", servers[i]);
			}
			ArrayList<String> server = new ArrayList<String>();
			server.addAll(Arrays.asList(servers));
			listAdapter = new ArrayAdapter<String>(this, R.layout.rowtextview, server);
			listAdapter.notifyDataSetChanged();
			serverList.setAdapter(listAdapter);
//			serverList.setVisibility(View.GONE);
//			serverList.setVisibility(View.VISIBLE);
			
		}		
		else{
			
			Log.d("Toast", "toast");
			serverList.setVisibility(View.GONE);
			
			Context context = getApplicationContext();
			CharSequence text = "No Game Servers Exist!";
			int duration = Toast.LENGTH_SHORT;

			Toast toast = Toast.makeText(context, text, duration);
			toast.show();
		}
	}
	
	@Override
	public void onResume(){
		super.onResume();
		startService(intent);
		registerReceiver(broadcastReceiver, new IntentFilter(ActionUpdate.BROADCAST_ACTION));
	}
	
	@Override
	public void onPause(){
		super.onPause();
		unregisterReceiver(broadcastReceiver);
		//stopService(intent);
	}

	

}
